package cn.edu.lingnan.servlet.project;

import cn.edu.lingnan.pojo.Project;
import cn.edu.lingnan.pojo.ProjectAdult;
import cn.edu.lingnan.pojo.User;
import cn.edu.lingnan.service.ProjectService;
import cn.edu.lingnan.service.ProjectServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/enterproject")
public class EnterProjectServlet extends HttpServlet {
    private ProjectService projectService = new ProjectServiceImp();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();

        String name = request.getParameter("name");
        System.out.println("申请加入姓名:" + name);
        Integer userId = Integer.parseInt(request.getParameter("userId"));
        Integer protectId = Integer.parseInt(request.getParameter("protectId"));
        String action = request.getParameter("action");

        // Retrieve the applied project IDs from session
        List<Integer> appliedProjectIds = (List<Integer>) session.getAttribute("appliedProjectIds");
        if (appliedProjectIds == null) {
            appliedProjectIds = new ArrayList<>();
        }

        if ("apply".equals(action)) {
            Integer i = projectService.StudentInsertProject(name, protectId, userId);
            System.out.println("发送审核: " + i);
            session.setAttribute("message", "已发送申请");
            appliedProjectIds.add(protectId);
        } else if ("cancel".equals(action)) {
            Integer i = projectService.deleteInsertProject(protectId);
            System.out.println("取消申请: " + i);
            session.setAttribute("message", "已取消申请");
            appliedProjectIds.remove(protectId);
        }
        List<Project> noprojects = projectService.queryNoProjects(name);
       request.getSession().setAttribute("noprojects", noprojects);

        User user= (User) session.getAttribute("user");
        List<ProjectAdult> projectAdults = projectService.studentqueryaduitProject(user.getId());
        session.setAttribute("projectAdults", projectAdults);
        // Update the applied projects list in the session
        session.setAttribute("appliedProjectIds", appliedProjectIds);

        response.sendRedirect("student_querynoproject.jsp");
    }
}